package com.owen.client.ui;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.web.bindery.requestfactory.gwt.client.DefaultRequestTransport;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.web.bindery.event.shared.EventBus;
import com.owen.client.ui.widget.ClassEditor;
import com.owen.liferay.shared.ClassProxy;
import com.owen.shared.AppRequestFactory;
import com.owen.shared.events.AddNewClassEvent;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.IsWidget;


public class ClassPresenter {

	private final Display display;
	private final EventBus eventBus;
	private final AppRequestFactory requestFactory;
	
	public interface Display extends IsWidget {
		
		CellTable getTable();
		ClassEditor getEditor();
		Button getAddNew();
	}
	
	public ClassPresenter (final Display display, final EventBus eventBus, final AppRequestFactory requestFactory) {
		this.display = display;
		this.eventBus = eventBus;
		this.requestFactory = requestFactory;
		
		GWT.log("Instantiating ClassPresenter...");
		
		final ClassEditorPresenter classPresenter = new ClassEditorPresenter(display.getEditor(), eventBus, requestFactory);
		
		// add the handler for adding new authors
		display.getAddNew().addClickHandler(new ClickHandler () {

			@Override
			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new AddNewClassEvent());
			}
			
		});
		
	}
	
	public void populateTable() {
		
		DefaultRequestTransport transport = new DefaultRequestTransport();
		transport.setRequestUrl("/demo-world-liferay-portlet/gwt/gwtRequest");
		requestFactory.initialize(eventBus, transport);
		GWT.log("url is: " + ((DefaultRequestTransport) requestFactory.getRequestTransport()).getRequestUrl());
		
		Request<List<ClassProxy>> findReq = requestFactory.classRequest().returnAllClasses();
		
		findReq.fire(new Receiver<List<ClassProxy>>() {

			@Override
			public void onSuccess(List<ClassProxy> classes) {
				GWT.log("Class list returned is: " + classes.size());
				
			    // Set the total row count. This isn't strictly necessary, but it affects
			    // paging calculations, so its good habit to keep the row count up to date.
			    display.getTable().setRowCount(classes.size(), true);

			    // Push the data into the widget.
			    display.getTable().setRowData(0, classes);
			}
			
		});		
	}
	
	public Display getDisplay() {
		return display;
	}
}
